import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"
import {
    pollutionFunc,
    getActivetiGoodsData,
    getDiscountActivityAcyucn,
    getDiscountActivityFarmet,
    getListNewUserGiftFarmet,
    getNewUserGiftFarme,
    getCouponListFarmet,
    getSurpriseTicketLisFarmet,
    getSurpriseTicketDataFarmet,
    getCouponDataFarmet,
    getPromotionListFlashFarmet,
    getpromotionListFlashItemFarmet
} from "../asyncGetData/activetDataFunc"
import {getshopFreightTemplateAsync} from "~store/controller/jinritemaiShops"
interface priceinfolistType {
    id: string,
    showPriter: number,
    turnLoading: boolean,
    originalPrice: string,
    nowPrice: string,
    activetiItem: any,
    tagname: string,
    goodTitleData: string,
    goodTagsData: string[]
}
export interface jinritemaiProduct {
    priceinfolist: [priceinfolistType],
    showAllStatus: boolean,
    activityToolType: number,
    ActivetiGoodsList: [],
    getActivetAllStatus: boolean,
    getDiscountActivityData: any,
    getDiscountActivityStatus: boolean,
    getDetailNewUserGiftAllDataState: any,
    getDetailNewUserGiftAllDataStatus: boolean,
    getSurpriseTicketLisAllDataState: any,
    getSurpriseTicketLisAllDataStatus: boolean,
    getCouponListAllDataState: any,
    getCouponListAllDataStatus: boolean,
    getPromotionListFlashAllDataState: any,
    getPromotionListFlashAllDataStatus: boolean,

    supTicket: any
}
// 获取转化后的详情
export const showPriceInfo = createAsyncThunk(
    "goods/setShowPriceInfo",
    async (_: any, { getState, dispatch }) => {
        const { jinritemaiProduct, jinritemaiShops } = getState() as any;
        const {
            priceinfolist,
            ActivetiGoodsList,
            getActivetAllStatus,
            getDiscountActivityStatus,
            getDiscountActivityData,
            getDetailNewUserGiftAllDataStatus,
            getDetailNewUserGiftAllDataState,
            getSurpriseTicketLisAllDataStatus,
            getSurpriseTicketLisAllDataState,
            getCouponListAllDataState,
            getCouponListAllDataStatus,
            getPromotionListFlashAllDataStatus,
            getPromotionListFlashAllDataState
        } = jinritemaiProduct
        const {
            shopFreightTemplateStatus
        } = jinritemaiShops
        const priceinfolistCopy: any = JSON.parse(JSON.stringify(priceinfolist))
        for (let i = 0; i < priceinfolistCopy.length; i++) {
            if (priceinfolistCopy[i].id === _ || _ === 'all') {
                priceinfolistCopy[i].turnLoading = true
                if (priceinfolistCopy[i].id === _) break
            }
        }
        if (!getActivetAllStatus) {
            dispatch(getGoodsAsync(_))
            return priceinfolistCopy
        }
        if (!getDiscountActivityStatus) {
            dispatch(getDiscountActivity(_))
            return priceinfolistCopy
        }
        if (!getDetailNewUserGiftAllDataStatus) {
            dispatch(getDetailNewUserGiftAllData(_))
            return priceinfolistCopy
        }

        // 惊喜券获取进度
        if (!getSurpriseTicketLisAllDataStatus) {
            dispatch(getSurpriseTicketLisAllData(_))
            return priceinfolistCopy
        }
        // 优惠券获取进度
        if (!getCouponListAllDataStatus) {
            dispatch(getCouponListAllData(_))
            return priceinfolistCopy
         }
         
         // 获取运费模板进度
         if(!shopFreightTemplateStatus) {
             dispatch(getshopFreightTemplateAsync(_))
             return priceinfolistCopy
         }
         // 拼团进度
         if(!getPromotionListFlashAllDataStatus) {
             dispatch(getPromotionListFlashAllData(_))
             return priceinfolistCopy
         }

        for (let i = 0; i < priceinfolistCopy.length; i++) {
            if (_ === 'all' || _ === priceinfolistCopy[i].id) {
                // 关闭加载状态
                priceinfolistCopy[i].turnLoading = false

                // 拼团活动
                const promotionListFlashItem = getpromotionListFlashItemFarmet(priceinfolistCopy[i].id, getPromotionListFlashAllDataState)
                priceinfolistCopy[i].isPint = false
                // 限时限量
                const activetiGoodItem = getActivetiGoodsData(priceinfolistCopy[i].id, ActivetiGoodsList) // 限时限量
                if(promotionListFlashItem.showstatus) {
                    // 拼团与优惠券新人礼金等存在冲突
                    if(activetiGoodItem.minPrice <=  promotionListFlashItem.minPrice) {
                        priceinfolistCopy[i].activetiGoodItem = activetiGoodItem
                    } else {
                        priceinfolistCopy[i].activetiGoodItem = promotionListFlashItem
                        priceinfolistCopy[i].isPint = true
                    }
                    if(!activetiGoodItem.minPrice  && promotionListFlashItem.minPrice) {
                        priceinfolistCopy[i].activetiGoodItem = promotionListFlashItem
                        priceinfolistCopy[i].isPint = true
    
                    }
                    if(activetiGoodItem.minPrice  && !promotionListFlashItem.minPrice) {
                        priceinfolistCopy[i].activetiGoodItem = activetiGoodItem
                    }
                } else {
                    priceinfolistCopy[i].activetiGoodItem = activetiGoodItem
                }
               
                // priceinfolistCopy[i].activetiItem = activetiGoodItem.getFindInfoter
                // priceinfolistCopy[i].originalPrice = activetiGoodItem.originalPrice
                // priceinfolistCopy[i].nowPrice = activetiGoodItem.nowPrice
                // priceinfolistCopy[i].tagname = activetiGoodItem.tagname
                // 满减
                const getDiscountActivityFarmetData = getDiscountActivityFarmet(priceinfolistCopy[i].id, getDiscountActivityData) // 满减
                priceinfolistCopy[i].getDiscountActivityFarmetData = getDiscountActivityFarmetData

                // 新人礼金
                const getNewUserGiftFarmeData = getNewUserGiftFarme(priceinfolistCopy[i].id, getDetailNewUserGiftAllDataState) // 新人礼金
                priceinfolistCopy[i].getNewUserGiftFarmeData = getNewUserGiftFarmeData // 新人礼金的优惠券

                // 惊喜券
                const getSurpriseTicketDataFarmetData = getSurpriseTicketDataFarmet(priceinfolistCopy[i].id, getSurpriseTicketLisAllDataState)
                priceinfolistCopy[i].supTicket = getSurpriseTicketDataFarmetData

                // 优惠券
                const getCouponDataFarmetData = getCouponDataFarmet(priceinfolistCopy[i].id, getCouponListAllDataState)

                priceinfolistCopy[i].couponData = getCouponDataFarmetData



                // 存储优惠券信息
                priceinfolistCopy[i].giftlist = []
                // console.log('getNewUserGiftFarmeData**--', getNewUserGiftFarmeData)
                //  && !priceinfolistCopy[i].isPint
                if (getNewUserGiftFarmeData.showstatus && !priceinfolistCopy[i].isPint) {
                    // console.log('getNewUserGiftFarmeData', getNewUserGiftFarmeData)
                    priceinfolistCopy[i].giftlist.push(getNewUserGiftFarmeData.shownumcontern)
                }
                // if(priceinfolistCopy[i].activetiGoodItem.showstatus) {
                //     priceinfolistCopy[i].showPriter = 1
                // }
                if (!priceinfolistCopy[i].activetiGoodItem.showstatus && (getDiscountActivityFarmetData.showstatus || getNewUserGiftFarmeData.showstatus || getSurpriseTicketDataFarmetData.length || getCouponDataFarmetData.length)) { // 或者其他的券
                    priceinfolistCopy[i].showPriter = 3
                } else if (priceinfolistCopy[i].activetiGoodItem.showstatus) {
                    priceinfolistCopy[i].showPriter = 1
                } else {
                    priceinfolistCopy[i].showPriter = 4
                }
                //  else {
                //     priceinfolistCopy[i].showPriter = 4
                // }
                if (_ === priceinfolistCopy[i].id) {
                    // console.log('priceinfolistCopy[i]', priceinfolistCopy[i])
                    break
                }
            }
        }
        return priceinfolistCopy
    }
)

// 获取参加限时限量购的链接 包括活动信息 商品sku信息
export const getGoodsAsync = createAsyncThunk(
    "goods/updataGoods",
    async (_: any, { dispatch }) => { // arg, { dispatch, getState, extra })
        const activetGoodsData: any = await pollutionFunc({ page: 1, size: 20, campaign_status: 2 });
        const returnData = []
        activetGoodsData.forEach((element: any) => {
            element.promotion_goods.forEach((item: any) => {
                for (let key in element) {
                    if (key !== 'promotion_goods') item[key] = element[key]
                }
                returnData.push(item)
            })
        });
        _ && setTimeout(() => { dispatch(showPriceInfo(_)) }, 137)

        return returnData;
    }
);

// 获取满减活动商品列表
export const getDiscountActivity = createAsyncThunk(
    'goods/setDiscountActivity',
    async (_: any, { dispatch }) => {
        const getActivityDatacontent = await getDiscountActivityAcyucn({ activity_status: '2', page: 1, pageSize: 20 }
        )
        _ && setTimeout(() => { dispatch(showPriceInfo(_)) }, 137)
        return getActivityDatacontent
    }
)

// 异步批量获取新人礼金商品列表
export const getDetailNewUserGiftAllData = createAsyncThunk(
    'goods/setDetailNewUserGiftAllData',
    async (_: any, { dispatch }) => {
        const getData = await getListNewUserGiftFarmet({ apply_status: 3, page: 1, pageSize: 20 }).catch(err => console.log(err))
        _ && setTimeout(() => { dispatch(showPriceInfo(_)) }, 137)
        return getData
    }
)

// 获取优惠券列表
export const getCouponListAllData = createAsyncThunk(
    'goods/setCouponListAllData',
    async (_: any, { dispatch }) => {
        const getData = await getCouponListFarmet({ page: 1, pageSize: 100 })
        _ && setTimeout(() => { dispatch(showPriceInfo(_)) }, 137)
        return getData
    }
)

// 获取惊喜券列表
export const getSurpriseTicketLisAllData = createAsyncThunk(
    'goods/setSurpriseTicketLisAllData',
    async (_: any, { dispatch }) => {
        const getData = await getSurpriseTicketLisFarmet({ page: 1, pageSize: 10 })
        _ && setTimeout(() => { dispatch(showPriceInfo(_)) }, 137)
        return getData
    }
)

// 获取拼团活动列表
export const getPromotionListFlashAllData = createAsyncThunk(
    'goods/setPromotionListFlashAllData',
    async (_: any, { dispatch }) => {
        const getData = await getPromotionListFlashFarmet({ page: 1, pageSize: 10 })
        _ && setTimeout(() => { dispatch(showPriceInfo(_)) }, 137)
        return getData
    }
)

// 列表获取 后期异步获取数据 修改缓存
const jinritemaiProduct = createSlice({
    name: "jinritemaiProduct",
    initialState: {
        priceinfolist: [],
        showAllStatus: false,
        activityToolType: 16,
        ActivetiGoodsList: [], // 限时间限量购活动商品列表
        getActivetAllStatus: false,
        getDiscountActivityData: [], // 新人礼金商品列表
        getDiscountActivityStatus: false,
        getDetailNewUserGiftAllDataState: [], // 满减活动链接列表
        getDetailNewUserGiftAllDataStatus: false,
        getSurpriseTicketLisAllDataState: [], // 惊喜券
        getSurpriseTicketLisAllDataStatus: false,
        getCouponListAllDataState: [], // 优惠券
        getCouponListAllDataStatus: false,
        getPromotionListFlashAllDataState: [], // 拼团
        getPromotionListFlashAllDataStatus: false,
        isBuyStatus: {
            status: false,
            title: '',
            url: ''
        }
    },
    reducers: {
        addUserShopItem: (state, action) => {
            const getfiter = state.priceinfolist.filter(res => res.id === action.payload.id)
            if (!getfiter || !getfiter.length) {
                const taberItem = action.payload
                if (state.showAllStatus) {
                    // 是都全局始终显示转化结果
                    // taberItem.showPriter = true
                }
                state.priceinfolist.push(taberItem)
            }

        },
        setactivityToolType: (state, action) => {
            state.activityToolType = action.payload * 1
        },
        setBuyStatus: (state, action) => {
            state.isBuyStatus = action.payload
            console.log('state.isBuyStatus', state.isBuyStatus)
        }
    },
    extraReducers: (builder) => {
        builder
            .addCase("goods/updataGoods", (state, action) => {
            })
            // 异步方法的pedding状态
            .addCase(getGoodsAsync.pending, (state) => {
            })
            // 异步方法的成功的状态
            .addCase(getGoodsAsync.fulfilled, (state, action: { payload: any }) => {
                state.ActivetiGoodsList = action.payload
                state.getActivetAllStatus = true
            })
            /**
             * state
             * action 当前的错误信息
             */
            .addCase(getGoodsAsync.rejected, (state, action) => {
            });
        builder.addCase(showPriceInfo.fulfilled, (state, action) => {
            state.priceinfolist = action.payload
        })
        builder.addCase(getDiscountActivity.fulfilled, (state, action: { payload: any }) => {
            state.getDiscountActivityData = action.payload
            state.getDiscountActivityStatus = true
        })
        builder.addCase(getDetailNewUserGiftAllData.fulfilled, (state, action: { payload: any }) => {
            state.getDetailNewUserGiftAllDataState = action.payload
            state.getDetailNewUserGiftAllDataStatus = true
        })
        builder.addCase(getSurpriseTicketLisAllData.fulfilled, (state, action: { payload: any }) => {
            state.getSurpriseTicketLisAllDataState = action.payload
            state.getSurpriseTicketLisAllDataStatus = true
        })
        builder.addCase(getCouponListAllData.fulfilled, (state, action: { payload: any }) => {
            state.getCouponListAllDataState = action.payload
            state.getCouponListAllDataStatus = true
        })
        builder.addCase(getPromotionListFlashAllData.fulfilled, (state, action: { payload: any }) => {
            state.getPromotionListFlashAllDataState = action.payload
            state.getPromotionListFlashAllDataStatus = true
        })

    },
})
// showPriceInfo
export const { addUserShopItem, setactivityToolType, setBuyStatus } = jinritemaiProduct.actions

export default jinritemaiProduct.reducer